package com.termux.project

import android.os.Bundle
import android.util.Log
import com.termux.R
import com.termux.frontend.config.NeoTermPath
import com.termux.frontend.logging.NLog
import com.termux.project.JNI.chDir
import com.termux.project.JNI.setEnv
import org.apache.commons.io.FileUtils
import org.libsdl.app.SDLActivity
import java.io.File
import java.io.IOException

class IdeaSDLActivity : SDLActivity() {
    // the default main program
    private var sdlmain: String? = "libmain.so"
    private var workDir: String? = ""
    private val LIB_DIR = NeoTermPath.USR_PATH + "/lib"

    // the SDL2 libraries version
    override fun onCreate(savedInstanceState: Bundle?) {
        sdlmain = intent.getStringExtra("sdlmain")
        workDir = intent.getStringExtra("work_dir")
        copyLibFile()
        setTheme(android.R.style.Theme_Holo_Light)
        super.onCreate(savedInstanceState)
    }

    // get arguments from intent
//    override fun getArguments(): Array<String> {
//        val args = intent.getStringExtra("args")
//        return if (args != null && !args.isEmpty()) {
//            //Log.i(TAG, args);
//            args.trim { it <= ' ' }.split(" ".toRegex()).toTypedArray()
//        } else {
//            super.getArguments()
//        }
//    }
//
//    // libmain.so (your SDL2 program, from intent)
//    override fun getMainSharedObject(): String {
//        return if (sdlmain != null && !sdlmain!!.isEmpty()) {
//            //Log.i(TAG, pathname);
//            sdlmain!!
//        } else {
//            super.getMainSharedObject()
//        }
//    }

    // copy libxxx.so to internal directory
    private fun copyLibFile() {
        if (sdlmain == null || sdlmain!!.isEmpty()) return
        sdlmain = sdlmain!!.trim { it <= ' ' }
        if (File(sdlmain).exists()) {
            val libDir = NeoTermPath.USR_PATH + "/tmp"
            val libFile = libDir + "/" + File(sdlmain).name
            if (!File(libDir).exists()) {
                File(libDir).mkdir()
            }
            try {
                FileUtils.copyFile(File(sdlmain), File(libFile))
                Runtime.getRuntime().exec("chmod 755 $libFile").waitFor()

                // Environment variables must be set, otherwise the program will not run correctly
                val pwd = intent.getStringExtra("work_dir")
                Log.i(TAG, "chdir to: $pwd")
                chDir(pwd)
                setEnv("PWD", pwd, true)

                // sdlmain = /data/user/0/com.termux.sdl/tmpdir/libxxx.so
                sdlmain = libFile
                intent.putExtra("fname", sdlmain)
                intent.putExtra("currdir", workDir)
            } catch (ex: IOException) {
                Log.e(TAG, "copy file failed: " + ex.message)
//                showErrorDialog(ex.message)
            } catch (ex: InterruptedException) {
                Log.e(TAG, "exec cmd failed: " + ex.message)
//                showErrorDialog(ex.message)
            }
        }
    }

//    override fun loadLibraries() {
//        SDL.load("$LIB_DIR/libc++_shared.so")
//        SDL.load("$sdlmain")
//    }

    override fun onStop() {
        super.onStop()
        deleteLibFile()
    }

    override fun onDestroy() {
        super.onDestroy()
        NLog.d("idea", "sdl destroyed")
        deleteLibFile()
    }

    // delete libxxx.so file in the internal directory
    private fun deleteLibFile() {
        // delete /data/user/0/com.termux.sdl/tmpdir/libxxx.so
        if (sdlmain != null && !sdlmain!!.isEmpty()) {
            val file = File(sdlmain)
            NLog.i(
                TAG,
                "delete sdlmain: " + file.absolutePath
            )
            if (file.exists()) {
                try {
                    FileUtils.forceDelete(file)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    companion object {
        private const val TAG = "IdeaSDLActivity"
    }
}